<!DOCTYPE html>
<html lang="cn">
<head>
    <meta charset="UTF-8" />
    <title>订餐管理系统</title>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="upImage.js"></script>
    <link
            rel="stylesheet"
            href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" />
    <link rel="stylesheet" href="dish-management.css" />
    <link rel="stylesheet" href="popNotification.css" />
    <link rel="stylesheet" href="通用新页面css.css" />
</head>
<body>
<div id="app">
    <div class="container">
        <!-- 侧边栏导航 -->
        <div class="sidebar">
            <a href="mainpage.html" class="sidebar-item">首页</a>
            <a href="dish-management.html" class="sidebar-item active">菜品管理</a>
            <a href="order-management.html" class="sidebar-item">订单管理</a>
            <a href="marketing-statistics.html" class="sidebar-item">营销统计</a>
            <a href="UserPage.html" class="sidebar-item">用户管理</a>
        </div>

        <!-- 主内容区 -->
        <div class="content">
            <div class="header">
                <h1>欢迎来到订餐管理系统</h1>
            </div>

            <!-- 搜索区域 -->
            <div class="search-area">
                <input
                        type="text"
                        v-model="searchName"
                        placeholder="请输入菜品名称" />
                <select v-model="searchCategoryId">
                    <option value="0">全部分类</option>
                    <option v-for="category in categories" :value="category.id">
                        {{ category.name }}
                    </option>
                </select>
                <button @click="searchBtn">查询</button>
                <button class="reset" @click="reset">重置</button>
                <button class="add" @click="addDish">新增</button>
            </div>

            <!-- 菜品列表表格 -->
            <table>
                <thead>
                <tr>
                    <th>ID</th>
                    <th>菜品图片</th>
                    <th>菜品名称</th>
                    <th>分类</th>
                    <th>价格</th>
                    <th>状态</th>
                    <th>             </th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody>
                <tr v-for="dish in dishes" :key="dish.id">
                    <td>{{ dish.id }}</td>
                    <td>
                        <img
                                v-if="dish.image"
                                :src="dish.image"
                                class="dish-image"
                                alt="菜品图片">
                        <span v-else>无图片</span>
                    </td>
                    <td>{{ dish.name }}</td>
                    <td>{{ getCategoryName(dish.categoryId) }}</td>
                    <td>{{ dish.price }}</td>
                    <td>{{ dish.status === 1 ? '起售' : '停售' }}</td>
                    <td>{{ dish.create_time }}</td>
                    <td class="operation">
                        <button class="edit" @click="editDish(dish.id)">编辑</button>
                        <button class="delete" @click="deleteDish(dish.id)">删除</button>
                    </td>
                </tr>
                </tbody>
            </table>

            <!-- 分页控件 -->
            <div class="pagination">
                <select v-model="pageSize">
                    <option value="5">5条/页</option>
                    <option value="10">10条/页</option>
                    <option value="15">15条/页</option>
                </select>
                <button @click="prevPage" :disabled="currentPage === 1">
                    上一页
                </button>
                <span>{{ currentPage }}</span>
                <button @click="nextPage">下一页</button>
                前往
                <input type="number" v-model.number="jumpPage" min="1" />
                页
                <button @click="goToPage">跳转</button>
            </div>
        </div>
    </div>
    <p v-if="invisibleADD">擦撒法立法弗利萨</p>

    <!-- 新增菜品弹窗 -->
    <div class="popNotification" v-if="invisibleAdd">
        <div class="form-card">
            <div class="form-header">
                <h1 class="form-title">
                    <i class="fa fa-cutlery"></i>菜品信息表单
                </h1>
            </div>
            <form class="form-content">
                <div class="form-group">
                    <label for="name" class="form-label"
                    >菜品名称 <span class="required-mark">*</span></label
                    >
                    <input
                            type="text"
                            id="name"
                            name="name"
                            maxlength="32"
                            class="form-input"
                            required
                            v-model="newDish.name"
                            placeholder="请输入菜品名称" />
                    <p class="form-hint">最多32个字符</p>
                </div>
                <div class="form-group">
                    <label for="categoryId" class="form-label"
                    >菜品分类 <span class="required-mark">*</span></label
                    >
                    <select
                            id="categoryId"
                            name="categoryId"
                            class="form-input"
                            v-model="newDish.categoryId"
                            required>
                        <option value="1">川菜</option>
                        <option value="2">粤菜</option>
                        <option value="3">鲁菜</option>
                        <option value="4">苏菜</option>
                        <option value="5">闽菜</option>
                        <option value="6">浙菜</option>
                        <option value="7">湘菜</option>
                        <option value="8">徽菜</option>
                    </select>
                    <p class="form-hint">选择菜品所属的分类</p>
                </div>
                <div class="form-group">
                    <label for="price" class="form-label"
                    >菜品价格<span class="required-mark">*</span></label
                    >
                    <input
                            type="number"
                            id="price"
                            name="price"
                            step="0.01"
                            min="0"
                            required
                            v-model="newDish.price"
                            class="form-input"
                            placeholder="请输入菜品价格" />
                    <p class="form-hint">保留两位小数的数值</p>
                </div>
                <div class="form-group">
                    <label for="image" class="form-label">图片路径</label>
                    <input
                            type="file"
                            id="image"
                            name="image"
                            class="form-input"
                            accept=".jpg,image/jpeg"
                            @change="getBase64" />
                    <p class="form-hint">仅支持JPG格式图片，文件大小建议不超过2MB</p>
                    <p
                            id="imageError"
                            class="form-error"
                            style="color: #ff8b8b; display: none">
                        请选择JPG格式的图片文件
                    </p>
                </div>
                <div class="form-group">
                    <label for="description" class="form-label">描述信息</label>
                    <textarea
                            id="description"
                            name="description"
                            v-model="newDish.description"
                            maxlength="255"
                            rows="3"
                            class="form-input"
                            placeholder="请输入菜品描述信息"></textarea>
                    <p class="form-hint">最多255个字符</p>
                </div>
                <div class="form-group">
                    <label class="form-label">销售状态</label>
                    <div class="radio-group">
                        <label class="radio-item">
                            <input
                                    type="radio"
                                    name="status"
                                    value="1"
                                    v-model="newDish.status" />
                            <span>起售</span>
                        </label>
                        <label class="radio-item">
                            <input
                                    type="radio"
                                    name="status"
                                    value="0"
                                    v-model="newDish.status" />
                            <span>停售</span>
                        </label>
                    </div>
                </div>
                <div class="form-actions">
                    <button type="reset" class="btn btn-reset">
                        <i class="fa fa-refresh"></i>重置
                    </button>
                    <button class="btn btn-cancel" @click="cancelAdd">
                        <i class="fa fa-save"></i>取消
                    </button>
                    <button
                            type="submit"
                            class="btn btn-submit"
                            @click.prevent="submitAdd">
                        <i class="fa fa-save"></i>保存
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- 编辑菜品弹窗 -->
    <div class="popNotification" v-if="invisibleEdit">
        <div class="form-card">
            <div class="form-header">
                <h1 class="form-title"><i class="fa fa-edit"></i>编辑菜品信息</h1>
            </div>
            <form class="form-content">
                <div class="form-group">
                    <label for="editId" class="form-label">菜品ID</label>
                    <input
                            type="text"
                            id="editId"
                            class="form-input"
                            v-model="editDishForm.id"
                            readonly />
                </div>
                <div class="form-group">
                    <label for="editName" class="form-label"
                    >菜品名称 <span class="required-mark">*</span></label
                    >
                    <input
                            type="text"
                            id="editName"
                            maxlength="32"
                            class="form-input"
                            required
                            v-model="editDishForm.name"
                            placeholder="请输入菜品名称" />
                </div>
                <div class="form-group">
                    <label for="editCategoryId" class="form-label"
                    >菜品分类 <span class="required-mark">*</span></label
                    >
                    <select
                            id="editCategoryId"
                            class="form-input"
                            v-model="editDishForm.categoryId"
                            required>
                        <option value="1">川菜</option>
                        <option value="2">粤菜</option>
                        <option value="3">鲁菜</option>
                        <option value="4">苏菜</option>
                        <option value="5">闽菜</option>
                        <option value="6">浙菜</option>
                        <option value="7">湘菜</option>
                        <option value="8">徽菜</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="editPrice" class="form-label"
                    >菜品价格<span class="required-mark">*</span></label
                    >
                    <input
                            type="number"
                            id="editPrice"
                            step="0.01"
                            min="0"
                            v-model="editDishForm.price"
                            class="form-input"
                            placeholder="请输入菜品价格"
                            required />
                </div>
                <div class="form-group">
                    <label for="editImage" class="form-label">图片路径</label>
                    <input
                            type="file"
                            id="editImage"
                            class="form-input"
                            accept=".jpg,image/jpeg"
                            @change="(e) => {
								const file = e.target.files[0];
								if (file && window.FileReader) {
									const reader = new FileReader();
									reader.readAsDataURL(file);
									reader.onload = (ev) => {
										editDishForm.image = ev.target.result;
									};
								}
							}" />
                    <p class="form-hint">仅支持JPG格式图片，文件大小建议不超过2MB</p>
                </div>
                <div class="form-group">
                    <label for="editDescription" class="form-label">描述信息</label>
                    <textarea
                            id="editDescription"
                            v-model="editDishForm.description"
                            maxlength="255"
                            rows="3"
                            class="form-input"
                            placeholder="请输入菜品描述信息"></textarea>
                </div>
                <div class="form-group">
                    <label class="form-label">销售状态</label>
                    <div class="radio-group">
                        <label class="radio-item">
                            <input
                                    type="radio"
                                    name="editStatus"
                                    value="1"
                                    v-model="editDishForm.status" />
                            <span>起售</span>
                        </label>
                        <label class="radio-item">
                            <input
                                    type="radio"
                                    name="editStatus"
                                    value="0"
                                    v-model="editDishForm.status" />
                            <span>停售</span>
                        </label>
                    </div>
                </div>
                <div class="form-actions">
                    <button type="button" class="btn btn-reset" @click="cancelEdit">
                        <i class="fa fa-times"></i>取消
                    </button>
                    <button type="button" class="btn btn-submit" @click="submitEdit">
                        <i class="fa fa-save"></i>保存修改
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>
</body>
<script>
    const { createApp, reactive, ref, onMounted } = Vue;
    createApp({
        setup() {
            // 状态数据定义
            const dishes = ref([
                {
                    id: 1,
                    name: "",
                    categoryId: 1,
                    price: 55,
                    image: "",
                    description: "",
                    status: 1
                }
            ]);
            const categories = ref([
                { id: 1, name: "川菜" },
                { id: 2, name: "粤菜" },
                { id: 3, name: "鲁菜" },
                { id: 4, name: "苏菜" },
                { id: 5, name: "闽菜" },
                { id: 6, name: "浙菜" },
                { id: 7, name: "湘菜" },
                { id: 8, name: "徽菜" }
            ]);

            // 查询参数
            const searchName = ref("");
            const searchCategoryId = ref("0");

            // 分页参数
            const currentPage = ref(1);
            const pageSize = ref(5);
            const jumpPage = ref(1);

            // 新增弹窗状态与数据
            const invisibleAdd = ref(false);
            const newDish = ref({
                id: 1,
                name: "",
                categoryId: 1,
                price: 0,
                image: "",
                description: "",
                status: 1
            });

            // 编辑弹窗状态与数据
            const invisibleEdit = ref(false);
            const editDishForm = ref({
                id: 0,
                name: "",
                categoryId: 0,
                price: 0,
                image: "",
                description: "",
                status: 1
            });

            // 工具方法
            const getCategoryName = categoryId => {
                const category = categories.value.find(c => c.id === categoryId);
                return category ? category.name : "未知分类";
            };

            // 图片处理
            const getBase64 = e => {
                const file = e.target.files[0];
                if (!file) {
                    console.log("未选择文件");
                    return;
                }
                console.log("选中的文件：", file); // 打印文件信息

                if (window.FileReader) {
                    const reader = new FileReader();
                    reader.readAsDataURL(file);
                    reader.onload = ev => {
                        newDish.value.image = ev.target.result;
                        console.log("base64 转换结果：", ev.target.result); // 转换成功后打印
                        console.log("newDish.image 赋值后：", newDish.value.image);
                    };
                    reader.onerror = err => {
                        console.error("FileReader 错误：", err); // 捕获读取错误
                    };
                } else {
                    console.log("浏览器不支持 FileReader");
                }
            };

            // 查询相关方法
            const searchBtn = () => {
                let currentPage_copy;
                currentPage_copy = currentPage.value;
                currentPage.value = 1;
                if(!search()){
                    currentPage.value = currentPage_copy;
                }
            }
            const search = async () => {
                try {
                    const requestData = {
                        pageNum: currentPage.value,
                        pageSize: pageSize.value,
                        dish: { name: searchName.value , categoryId: searchCategoryId.value}
                    };
                    const response = await axios.post(
                        "/dish/listPageDish",
                        requestData,
                        {
                            headers: {
                                "Content-Type": "application/json",
                                Authorization: "Bearer " + localStorage.getItem("food_token")
                            },
                            timeout: 5000
                        }
                    );
                    if (Array.isArray(response.data.data)) {
                        dishes.value = response.data.data;
                        console.log(dishes.value);
                        return true;
                    } else console.log("查询失败：后端返回格式异常");
                } catch (error) {
                    console.error("菜品分页查询失败：", error);
                    alert(
                        error.response
                            ? `查询失败（${error.response.status}）：${
                                error.response.data || "服务器处理异常"
                            }`
                            : error.request
                            ? "查询失败：网络连接异常"
                            : "查询失败：请求参数格式错误"
                    );
                }
                return false;
            };

            // 页面加载完成后自动执行搜索
            onMounted(() => {
                search();
            });

            const reset = () => {
                searchName.value = "";
                searchCategoryId.value = "";
            };

            // 分页方法
            const prevPage = () => {
                if (currentPage.value > 1) {
                    currentPage.value--;
                    search();
                }
            };

            const nextPage = () => {
                currentPage.value++;
                search();
            };

            const goToPage = () => {
                if (jumpPage.value >= 1) {
                    currentPage.value = jumpPage.value;
                    search();
                } else alert("请输入正确的跳转页面！");
            };

            // 新增菜品相关方法
            const addDish = () => (invisibleAdd.value = true);

            const cancelAdd = () => {
                invisibleAdd.value = false;
                // 清空新增表单
                newDish.value = {
                    name: "",
                    categoryId: 1,
                    price: 0,
                    image: "",
                    description: "",
                    status: 1
                };
                document.getElementById("image").value = "";
            };

            const submitAdd = async () => {
                console.log("保存");
                if (newDish.value.name === "" || newDish.value.categoryId === "") {
                    alert("必选项不得为空");
                    return;
                }
                try {
                    console.log("保存的新菜单：", newDish.value);
                    const response = await axios.post("/dish/save", newDish.value, {
                        headers: {
                            "Content-Type": "application/json",
                            Authorization: "Bearer " + localStorage.getItem("food_token")
                        },
                        timeout: 5000
                    });
                    if (response.data.msg === "添加成功") {
                        console.log("添加成功");
                        invisibleAdd.value = false;
                        // 清空新增表单
                        newDish.value = {
                            name: "",
                            categoryId: 1,
                            price: 0,
                            image: "",
                            description: "",
                            status: 1
                        };
                        // 重置文件输入框
                        document.getElementById("image").value = "";
                        await search();
                        alert("添加成功");
                    } else console.log("添加失败：后端返回格式异常");
                } catch (error) {
                    console.log('失败')
                }
            };

            // 编辑菜品相关方法
            const editDish = id => {
                const dish = dishes.value.find(d => d.id === id);
                if (dish) {
                    editDishForm.value = JSON.parse(JSON.stringify(dish));
                    invisibleEdit.value = true;
                }
            };

            const cancelEdit = () => {
                invisibleEdit.value = false;
                // 清空编辑表单
                editDishForm.value = {
                    id: 0,
                    name: "",
                    categoryId: 0,
                    price: 0,
                    image: "",
                    description: "",
                    status: 1
                };
                document.getElementById("editImage").value = "";
            };

            const submitEdit = async () => {
                if (
                    editDishForm.value.name === "" ||
                    editDishForm.value.categoryId === "" ||
                    editDishForm.value.price === ""
                ) {
                    alert("必选项不得为空");
                    return;
                }
                try {
                    const response = await axios.post("/dish/updateAll", editDishForm.value, {
                        headers: {
                            "Content-Type": "application/json",
                            Authorization: "Bearer " + localStorage.getItem("food_token")
                        },
                        timeout: 5000
                    });
                    if (response.data.msg === "修改成功") {
                        console.log("修改成功");
                        invisibleEdit.value = false;
                        // 清空编辑表单
                        editDishForm.value = {
                            id: 0,
                            name: "",
                            categoryId: 0,
                            price: 0,
                            image: "",
                            description: "",
                            status: 1
                        };
                        // 重置文件输入框
                        document.getElementById("editImage").value = "";
                        await search();
                        alert("修改成功");
                    } else console.log("修改失败：后端返回格式异常");
                } catch (error) {
                    // 错误处理保持不变
                }
            };

            // 删除菜品方法
            const deleteDish = async id => {
                if (confirm("确定要删除该菜品吗？")) {
                    try {
                        const requestData = {
                            id:id
                        };
                        console.log(requestData.id)
                        const response = await axios.delete(
                            "/dish/delete",
                            {
                                data: requestData,
                                headers: {
                                    "Content-Type": "application/json",
                                    Authorization: "Bearer " + localStorage.getItem("food_token")
                                },
                                timeout: 5000
                            }
                        );
                        if (response.data.msg === '删除成功') {
                            console.log("删除成功");
                            invisibleEdit.value = false;
                            await search();
                            alert("删除成功");
                        }

                        else console.log("删除失败：后端返回格式异常");
                    } catch (error) {
                        console.error("删除失败：", error);
                        alert(
                            error.response
                                ? `删除失败（${error.response.status}）：${
                                    error.response.data || "服务器处理异常"
                                }`
                                : error.request
                                ? "删除失败：网络连接异常"
                                : "删除失败：请求参数格式错误"
                        );
                    }
                }
            };

            return {
                dishes,
                categories,
                searchName,
                searchCategoryId,
                currentPage,
                pageSize,
                jumpPage,
                invisibleAdd,
                newDish,
                invisibleEdit,
                editDishForm,
                getCategoryName,
                getBase64,
                search,
                reset,
                prevPage,
                nextPage,
                goToPage,
                addDish,
                cancelAdd,
                submitAdd,
                editDish,
                cancelEdit,
                submitEdit,
                deleteDish,
                searchBtn
            };
        }
    }).mount("#app");
</script>
</html>
